import {
  Form, Row, Col, Input, Select, InputNumber, message,
  Space, Button, Drawer, Divider
} from 'antd';
import {useEffect, useState} from 'react';
import {connect} from 'umi';
import BraftEditor from "braft-editor";
import 'braft-editor/dist/index.css';
import {normFile, uuid, uploadAliyunOSS} from "@/utils/upload";
import {CONTROLS} from "@/constants";
import AliyunOSSUploadFile from '@/components/AliyunOSSUploadFile/App';

const DataForm = (props) => {
  const {dispatch, submitting} = props;
  const {dataForm, setDataForm, tablePayload, setTablePayload, selectedId} = props.data;
  const [form] = Form.useForm();
  const [editorState, setEditorState] = useState(null);
  const [cover, setCover] = useState([]);
  const [video, setVideo] = useState([]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({status: 1, orderby: 0});
    }
    if (dataForm && dataForm.data) {
      let cover_ = [];
      if (dataForm.data.cover) {
        cover_ = [{uuid: uuid(), name: dataForm.data.cover.split("/").pop(), status: 'done', url: dataForm.data.cover}];
      }
      setCover(cover_)

      let video_ = [];
      if (dataForm.data.video) {
        video_ = [{uuid: uuid(), name: dataForm.data.video.split("/").pop(), status: 'done', url: dataForm.data.video}];
      }
      setVideo(video_)

      form.setFieldsValue({
        ...dataForm.data,
        cover: cover_,
        video: video_,
        detail: BraftEditor.createEditorState(dataForm.data.detail)
      });
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      values.placeId = selectedId;
      if (values.placeId <= 0) {
        message.error('请选择推荐位').then();
        return;
      }

      values.detail = editorState ? editorState.toHTML() : '';

      if (values.cover && (values.cover.length > 0)) {
        values.cover = values.cover.filter(d => d.status === 'done').pop().url;
      } else {
        values.cover = '';
      }

      if (values.video && (values.video.length > 0)) {
        values.video = values.video.filter(d => d.status === 'done').pop().url;
      } else {
        values.video = '';
      }

      dispatch({
        type: values.id ? 'PCmsPlaceRight/edit' : 'PCmsPlaceRight/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setCover([]);
    setVideo([]);
    setEditorState(null);
    setDataForm(undefined);
    form.resetFields();
  }

  return (
    <Drawer
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onClose={onCancel}
      forceRender={true}
      width={1300}
      styles={{header: {padding: '8px 24px'}, body: {overflow: 'hidden'}}}
      extra={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button loading={submitting} onClick={onOk} type="primary">提交</Button>
        </Space>
      }
    >
      <Form layout='horizontal' labelCol={{span: 6}} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='title' label='标题'
              rules={[
                {required: false, message: '标题不能为空'},
              ]}>
              <Input placeholder='请输入标题'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='tag' label='标签'
              rules={[
                {required: false, message: '标签不能为空'},
              ]}>
              <Input placeholder='请输入标签'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name={'cover'} label="封面图片"
              rules={[
                {required: false, message: '封面图片不能为空'},
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUploadFile
                data={{
                  images: cover, setImages: setCover, size: 10, len: 1, accept: 'image/*',
                  placeholder: '请选择封面图片'
                }}/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name={'video'} label="视频文件"
              rules={[
                {required: false, message: '视频文件不能为空'},
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUploadFile
                data={{
                  images: video, setImages: setVideo, size: 10, len: 1, accept: 'video/*',
                  placeholder: '请选择视频文件'
                }}/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='link' label='链接'
              rules={[
                {required: false, message: '链接不能为空'},
              ]}>
              <Input placeholder='请输入链接'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='param' label='参数'
              rules={[
                {required: false, message: '参数不能为空'},
              ]}>
              <Input placeholder='请输入参数'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='status' label='当前状态'
              rules={[
                {required: true, message: '当前状态不能为空'},
              ]}
            >
              <Select placeholder='请选择当前状态'>
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='orderby' label='排序属性'
              rules={[
                {required: true, message: '排序属性不能为空'},
              ]}>
              <InputNumber style={{width: '100%'}} placeholder='请输入排序属性'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              labelCol={{span: 6}}
              name='description' label='描述'
              rules={[
                {required: false, message: '描述不能为空'},
              ]}>
              <Input.TextArea rows={3} placeholder='推荐位描述'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              labelCol={{span: 6}}
              name='remark' label='备注信息'
              rules={[
                {required: false, message: '备注信息不能为空'},
              ]}
            >
              <Input.TextArea rows={3} placeholder='请输入备注信息'/>
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{marginTop: -8}}/>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{span: 3}}
              name='detail' label='详情'
              rules={[
                {required: false, message: '详情不能为空'},
              ]}>
              <BraftEditor
                CONTROLS={CONTROLS}
                contentStyle={{height: 200, overflowX: 'auto'}}
                style={{border: '1px solid #ddd', borderRadius: 4}}
                media={{uploadAliyunOSS, accepts: {audio: false}}}
                onChange={e => setEditorState(e)}
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};


export default connect(({loading, PCmsPlaceLeft}) => {
  return {
    submitting: loading.effects['PCmsPlaceRight/add'] || loading.effects['PCmsPlaceRight/edit'],
    placeList: PCmsPlaceLeft.list,
  };
})(DataForm);

